from django.shortcuts import render
from rest_framework import status
from rest_framework.mixins import ListModelMixin, CreateModelMixin, UpdateModelMixin
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet

from .serializers import RegisterCreateUserSerializer, UserCenterInfoSerializer, EmailUpdateSerializer, \
    AddressSerializer
# from .models import User
# from mall.apps.users.models import User

# from apps.users.models import User  # 运行报错 多了apps

from users.models import User
from rest_framework.generics import ListAPIView, CreateAPIView, GenericAPIView


# Create your views here.

# APIView
# GenericAPIView
# ListAPIView ,CreateAPIView

class RegisterUserNameView(APIView):

    """
    GET     /users/usernames/(?P<username>\w{5,20})/count/


    GET     /users/usernames/?username=xxx
    POST    /users/usernames/           username=xxxx

    """

    def get(self,request,username):
        # 查询数据库 看有没有制定的数据
        count = User.objects.filter(username=username).count()
        # count = 0 不存在
        # count >= 1  存在

        context = {
            'count':count,
            'username':username     # 想返回就返回,不返回 它要数据再返回
        }

        return Response(context)


# APIView

# GenericAPIView
# ListAPIView ,CreateAPIView
# 注册是使用POST方式提交所以使用CreateAPIView
# 因为数据要入库，并且用到了序列化操作，所以使用三级视图CreateAPIView

class RegisterCreateUserView(CreateAPIView):
    # post   users/

    # 获取到username,password,password2,sms_code,allow,mobile

    # 调用序列化器进行校验

    # 入库


    serializer_class = RegisterCreateUserSerializer




from rest_framework.permissions import IsAuthenticated
class UserCenterInfoView(GenericAPIView):
    """
    1.访问个人中心必须的登陆用户  IsAuthenticated 只能是认证用户
    2.得到登陆的用户 得到的用户模型用序列化器转换为json数据

    """
    # 访问个人中心必须的登陆用户
    # 必须是登录用户
    permission_classes = [IsAuthenticated]

    serializer_class = UserCenterInfoSerializer

    def get(self, request):
        # 用户的模型如何获取
        user = request.user

        serializer = self.get_serializer(instance=user)

        return Response(serializer.data)

from rest_framework.generics import RetrieveAPIView
class UserCenterInfo2View(RetrieveAPIView):



    permission_classes = [IsAuthenticated]

    serializer_class = UserCenterInfoSerializer

    # queryset = User.objects.all()

    # 重写方法,返回 用户模型
    def get_object(self):
        return self.request.user


"""
1.当用户输入邮箱的时候,保存邮箱信息
2.需要发送一个邮件给用户
3.需要记录邮件的激活状态
4.如何发送邮件(邮件的url),如何记录邮件
"""
from .models import User
from rest_framework.generics import UpdateAPIView
class EmailUpdateView(UpdateAPIView):
    # 把用户提交的信息提交过来
    # 更新email信息
    permission_classes = [IsAuthenticated]

    serializer_class = EmailUpdateSerializer

    # 重写方法,返回 用户模型
    def get_object(self):
        return self.request.user





class VerificationEmailView(APIView):

    """
    验证激活邮箱
    GET  /users/emails/verification/?token=xxxx
    获取token
    判断token是否存在,并有token获取用户的id
    查询数据库判断用户是否存在
    修改用户邮箱激活状态
    返回响应

    """
    def get(self,request):

        # 获取token
        token = request.query_params.get('token')
        if not token:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        user = User.check_verify_email_token(token)

        if user is None:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        else:
            user.email_active = True

            user.save()

            return Response({'message':"ok"})












from rest_framework.decorators import action
from .serializers import AddressTitleSerializer

from .serializers import UserHistorySerilizer,SKUSerializer
from goods.models import SKU
from django_redis import get_redis_connection
#  保存和查看
class UserHistoryView(GenericAPIView):
    """
    1.只记录登陆用户的信息,需要设置权限
    2.前端发送一个请求,里面包含用户信息和商品id
    3.判断商品id是否存在
    4.将记录信息保存在redis中

    """
    permission_classes = [IsAuthenticated]

    serializer_class = UserHistorySerilizer


    def post(self,request):

        # 创建序列化器,对数据进行校验
        serializer = self.get_serializer(data=request.data,context={"request":request})
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response({"message": 'ok'})


    def get(self,request):
        """
        1. 既然是用户的历史记录,肯定是登录用户
        2. 用户的历史记录在redis中,我们从redis中获取数据
        3. 根据id查询商品信息
        4. 将模型转换为 JSON
        """
        user = request.user

        redis_conn = get_redis_connection("history")

        ids = redis_conn.lrange('history_%s' % user.id, 0, 5)

        # 定义一个列表来存放数据
        skus = []

        for id in ids:
            skus = SKU.objects.get(pk=id)

            skus.append(SKU)

        # 序列化器
        serializer = SKUSerializer(skus,many=True)


class AddressViewSet(ListModelMixin,CreateModelMixin,UpdateModelMixin,GenericViewSet):
    """
    用户地址新增与修改
    list GET: /users/addresses/
    create POST: /users/addresses/
    destroy DELETE: /users/addresses/
    action PUT: /users/addresses/pk/status/
    action PUT: /users/addresses/pk/title/
    """

    #制定序列化器
    serializer_class = AddressSerializer
    #添加用户权限
    permission_classes = [IsAuthenticated]
    #由于用户的地址有存在删除的状态,所以我们需要对数据进行筛选
    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    def create(self, request, *args, **kwargs):
        """
        保存用户地址数据
        """
        count = request.user.addresses.count()
        if count >= 20:
            return Response({'message':'保存地址数量已经达到上限'},status=status.HTTP_400_BAD_REQUEST)

        return super().create(request,*args,**kwargs)

    def list(self, request, *args, **kwargs):
        """
        获取用户地址列表
        """
        # 获取所有地址
        queryset = self.get_queryset()
        # 创建序列化器
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        # 响应
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': 20,
            'addresses': serializer.data,
        })

    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    @action(methods=['put'], detail=True)
    def title(self, request, pk=None, address_id=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

    @action(methods=['put'], detail=True)
    def status(self, request, pk=None, address_id=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)


from rest_framework_jwt.views import ObtainJSONWebToken
from carts.utils import merge_cookie_to_redis

class UserAuthorizationView(ObtainJSONWebToken):

    def post(self, request):
        # 调用jwt扩展的方法，对用户登录的数据进行验证
        response = super().post(request)

        # 如果用户登录成功，进行购物车数据合并
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            # 表示用户登录成功
            user = serializer.validated_data.get("user")
            # 合并购物车
            #merge_cookie_to_redis(request, user, response)
            response = merge_cookie_to_redis(request, user, response)

        return response





































